package leetcode_core.leetcode_6;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述
 *
 * @author: 张庭杰
 * @date: 2023年01月31日 18:30
 */
public class CountSmaller {
    //由于在计算过程中会对数组进行排序,因此需要记录下原数组的下标
    private class Pair{
        public int val;
        public int index;
    }
    private Pair[] memo;
    private int[] count;
    public List<Integer> countSmaller(int[] nums) {
        memo = new Pair[nums.length];
        count = new int[nums.length];
        Pair[] nums2 = new Pair[nums.length];

        for(int i = 0;i< nums.length;i++){
            nums2[i] = new Pair();
            nums2[i].val = nums[i];
            nums2[i].index = i;
        }
        sort(nums2,0, nums.length-1);
        List<Integer> list = new ArrayList<>(nums.length);
        for (int number : count) {
            list.add(number);
        }
        return list;
    }
    private void sort(Pair[] nums,int lo,int hi){
        if(lo == hi){
            return;
        }
        //后序遍历
        int mid = lo + ((hi - lo)>>1);
        sort(nums,lo,mid);
        sort(nums,mid+1,hi);
        merge(nums,lo,mid,hi);
    }

    private void merge(Pair[] nums,int lo,int mid,int hi){
        //先复制一份
        for(int i = lo;i<=hi;i++){
            memo[i] = nums[i];
        }
        int i = lo;
        int j = mid+1;
        for(int p = lo;p<=hi;p++){
            if(i == mid +1){//证明左边全部比当前右边未归位的都要小,不结算
                nums[p] = memo[j++];
            }else if(j == hi+1){//证明左边此时未归位的比当前右边的全部都大结算,区间是[mid+1,hi],个数就是hi-mid
                nums[p] = memo[i++];
                count[nums[p].index] += hi - mid;
            }else if(memo[i].val  <= memo[j].val){//此处结算
                nums[p] = nums[i++];
                count[nums[p].index] += j-1-mid;
            }else{//
                nums[p] = nums[j++];
            }
        }
    }
    @Test
    public void test(){

    }

}
